package pingan.com.imandtwo.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import pingan.com.imandtwo.MainActivity;
import pingan.com.imandtwo.R;
import pingan.com.imandtwo.beans.LoginBean;
import pingan.com.imandtwo.interfaces.Iview;
import pingan.com.imandtwo.presenter.HttpPresenter;
import pingan.com.imandtwo.utils.BaseActivity;

/**
 * on 2018/2/5.
 * 登录界面
 */
public class LogoActivity extends BaseActivity implements Iview {

    @BindView(R.id.land_editText_name)
    EditText editText;
    @BindView(R.id.land_editText_pwd)
    EditText editText2;
    @BindView(R.id.land_textView_forget)
    TextView textView3;
    @BindView(R.id.land_textView_register)
    TextView zhuce;
    @BindView(R.id.land_button_land)
    Button logo;
    @BindView(R.id.edit_yanzhen)
    EditText editYanzhen;
    @BindView(R.id.yanzhengma)
    ImageView yanzhengma;
    @BindView(R.id.land_relativeLayout)
    RelativeLayout landRelativeLayout;
    private Unbinder bind;
    private HttpPresenter presenter;
    private   Bitmap bm = null;
    private String name;
    private String psd;
    private int aa=3;
    private Handler whand=new Handler(){


        @Override
        public void handleMessage(Message msg) {


            super.handleMessage(msg);
        }

    };
    private static final String TAG = "LogoActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logo);
        bind = ButterKnife.bind(this);

        presenter = new HttpPresenter(this);

        //获取验证码
        getPicture("http://www.bwstudent.com/instantMessaging/user/verification");
    }

    @OnClick({R.id.land_textView_forget, R.id.land_textView_register, R.id.land_button_land,R.id.yanzhengma})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //忘记密码
            case R.id.land_textView_forget:
                Intent intent1 = new Intent(LogoActivity.this,UpdatePsdActivity.class);
                startActivity(intent1);
                break;

            //验证码
            case R.id.yanzhengma:
                bm=null;
                getPicture("http://www.bwstudent.com/instantMessaging/user/verification");
                break;

            //注册
            case R.id.land_textView_register:
                Intent intent = new Intent(LogoActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
                break;

            //登录
            case R.id.land_button_land:
                name = editText.getText().toString().trim();
                psd = editText2.getText().toString().trim();

                //判空
                if (panduannull(name, psd)) {
                    if(isPhone(name)){
                        String yanzheng = editYanzhen.getText().toString();
                        HashMap<String, String> map = new HashMap<>();
                    map.put("phoneNumber", name);
                    map.put("password", psd);
                    map.put("imagevaildate", yanzheng);
                    presenter.getMap(map, "登录");
                    }else{
                        Toast.makeText(LogoActivity.this,"手机格式不正确!",Toast.LENGTH_SHORT).show();
                    }
                }



                break;
        }
    }

    //登陆非空判断
    public Boolean panduannull(String username, String userpsd) {
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(LogoActivity.this, "账户名为空!", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(userpsd)) {
            Toast.makeText(LogoActivity.this, "密码为空!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //手机号判断
    public Boolean isPhone(String username) {
        //正则表达式
        String regex = "^1[3|4|5|7|8]\\d{9}";
        return Pattern.matches(regex, username);
    }

    //获取验证码
    public void getPicture(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    URL url = new URL(path);
                    URLConnection connection = url.openConnection();
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();
                    bm = BitmapFactory.decodeStream(inputStream);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            yanzhengma.setImageBitmap(bm);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    //网络请求成功
    @Override
    public void onSuccess(Object o, String tag) {

        if (tag.equals("登录")) {
            LoginBean loginBean = (LoginBean) o;
            if (loginBean.getStatus().equals("0000")) {
                Toast.makeText(LogoActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                //保存账号
//                SharedPreferences shared = getSharedPreferences("User", MODE_PRIVATE);
//                SharedPreferences.Editor edit = shared.edit();
//                edit.putInt("UserId",loginBean.getResult().getUserId());
//                edit.commit();

                //执行登录功能
                EMClient.getInstance().login(name,//登录名称
                        psd,//登录密码

                        new EMCallBack() {//子线程执行，不能更新UI
                            @Override
                            public void onSuccess() {
                                //登录成功
                                Intent intent1 = new Intent(LogoActivity.this, MainActivity.class);
                                startActivity(intent1);
                                finish();
                            }

                            @Override
                            public void onError(int i, String s) {
                                //登录失败
                                Log.e("TAG", "登录失败失败:" + s);
                            }

                            @Override
                            public void onProgress(int i, String s) {
                                //进度更新
                            }
                        });
            } else {
                Toast.makeText(LogoActivity.this, loginBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.disAttach();
        bind.unbind();
        finish();
    }

}
